package com.hsmpay.utils;

import java.io.IOException;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.log4j.Logger;
import com.hsmpay.yl8583.utils.TestDes;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
 * 3DES加密
 * 
 * @version 1.0
 * @author
 * 
 */
public abstract class DesUtil {
	static Logger log = Logger.getLogger(DesUtil.class);
	
	/**
	 * 密钥算法
	 * @version 1.0
	 * @author
	 */
	public static final String KEY_ALGORITHM = "DESede";
		
	/**
	 * 加密/解密算法/工作模式/填充方式
	 * @version 1.0
	 * @author
	 */	
	public static final String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
	/**
	 * DES密钥算法
	 * @version 1.0
	 * @author
	 */
	private final static String DES = "DES";
	/**
	 * 加密/解密算法/工作模式/填充方式
	 * @version 1.0
	 * @author
	 */
	private final static String CIPHER_ALGORITHM_NEW = "DES/ECB/NoPadding";

	/**
	 * 转换密钥
	 * @param key 二进制密�?
	 * @return key 密钥
	 * 
	 */	
	public static Key toKey(byte[] key) throws Exception{
		//实例化DES密钥材料
		DESedeKeySpec dks = new DESedeKeySpec(key);
		//实例化秘密密钥工�?
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
		//生成秘密密钥
		return keyFactory.generateSecret(dks);
	}

	/**
	 * 解密
	 * @param data 待解密数�?
	 * @param key 密钥
	 * @return byte[] 解密数据
	 */	
	public static byte[] decrypt(byte[] data, byte[] key)throws Exception{
		//还原密钥
		Key k = toKey(key);
		//"DESede/ECB/NoPadding"
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		//初始化，设置为解密模�?
		cipher.init(Cipher.DECRYPT_MODE, k);
		//执行操作
		return cipher.doFinal(data);
	}
	/**
	 * 3DES解密
	 * @param dataS 待解密数�?
	 * @param keys 密钥
	 * @return byte[] 解密数据
	 */
	public static String decode3DES(String dataS, String keys){
		String result="";
		 try {
			 	byte[] data=hexStringToByte(dataS);
			 	byte[] key=hexStringToByte(keys);
				byte[] km = new byte[24];
				System.arraycopy(key, 0, km, 0, 16);
				System.arraycopy(key, 0, km, 16, 8);
				Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
				DESedeKeySpec dks = new DESedeKeySpec(km);
				SecretKey k = SecretKeyFactory.getInstance("DESede")
						.generateSecret(dks);
				cipher.init(Cipher.DECRYPT_MODE, k);
				result=byte2hex(cipher.doFinal(data));
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException("" + e);
			}
			return result;
	 }
	/**
	 * 3DES解密
	 * @param data 待解密数�?
	 * @param key 密钥
	 * @return byte[] 解密数据
	 */
	public static byte[] decode3DES(byte[] data, byte[] key){
		byte[] result;
		try {
			byte[] km = new byte[24];
			System.arraycopy(key, 0, km, 0, 16);
			System.arraycopy(key, 0, km, 16, 8);
			Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
			DESedeKeySpec dks = new DESedeKeySpec(km);
			SecretKey k = SecretKeyFactory.getInstance("DESede")
					.generateSecret(dks);
			cipher.init(Cipher.DECRYPT_MODE, k);
			result=cipher.doFinal(data);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("" + e);
		}
		return result;
	}
	/**
	 * 3DES加密
	 * @param data 待加密数�?
	 * @param key 密钥
	 * @return byte[] 加密数据
	 */
	public static byte[] compute3DES(byte[] key, byte[] data) {
		try {
			byte[] km = new byte[24];
			System.arraycopy(key, 0, km, 0, 16);
			System.arraycopy(key, 0, km, 16, 8);
			Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
			DESedeKeySpec dks = new DESedeKeySpec(km);
			SecretKey k = SecretKeyFactory.getInstance("DESede")
					.generateSecret(dks);
			cipher.init(Cipher.ENCRYPT_MODE, k);
			byte[] result = cipher.doFinal(data);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("" + e);
		}
	}
	/**
	 * 3DES加密
	 * @param dataS 待加密数�?
	 * @param keys 密钥
	 * @return byte[] 加密数据
	 */
	public static String encrypt3DES(String dataS, String keys){
		String result="";
		 try {
			 	byte[] data=hexStringToByte(dataS);
			 	System.out.println("data.length: " + data.length);
			 	byte[] key=hexStringToByte(keys);
				byte[] km = new byte[24];
				System.arraycopy(key, 0, km, 0, 16);
				System.arraycopy(key, 0, km, 16, 8);
				Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
				DESedeKeySpec dks = new DESedeKeySpec(km);
				SecretKey k = SecretKeyFactory.getInstance("DESede")
						.generateSecret(dks);
				cipher.init(Cipher.ENCRYPT_MODE, k);
				result=byte2hex(cipher.doFinal(data));
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException("" + e);
			}
			return result;
	 }

	/**
	 * 3DES加密
	 * @param data 待加密数
	 * @param keys 密钥 24字节长度
	 * @return byte[] 加密数据
	 */
	public static String encryptThreeDES(byte[] data, String keys){
		String result="";
		try {
			byte[] key=hexStringToByte(keys);
			SecretKey secretKey = new SecretKeySpec(key, "DESede");
			Cipher c1 = Cipher.getInstance("DESede");
			c1.init(Cipher.ENCRYPT_MODE, secretKey);
			byte[] res = c1.doFinal(data);
			result = byte2hexString(res);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("" + e);
		}
		return result;
	}


	public static String byte2hexString(byte[] b) {
		String hs="";
		String stmp="";

		for (int n=0;n<b.length;n++) {
			stmp=(java.lang.Integer.toHexString(b[n] & 0Xff));
			if (stmp.length()==1)
				hs=hs+"0"+stmp;
			else
				hs=hs+stmp;
			//if (n<b.length-1)  hs=hs+":";
		}
		return hs.toLowerCase();
	}
	//DES解密
	public static byte[] decodc(byte[] myinfo,byte[] key) {
		String Algorithm = "DES"; //DES,DESede,Blowfish
		try {
			DESKeySpec dks = new DESKeySpec(key);

			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Algorithm);
			SecretKey deskey = keyFactory.generateSecret(dks);

			//log.debug("解密前数据=[" + byte2hex(myinfo)+"]");

			Cipher c1 = Cipher.getInstance("DES/ECB/NoPadding");
			c1.init(Cipher.DECRYPT_MODE, deskey);

			byte[] cipherByte = c1.doFinal(myinfo);
			//log.debug("解密结果=[" + byte2hex(cipherByte)+"]");
			return cipherByte;

		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return null;
	}

	/**
	 * des解密
	 * @param myinfoS
	 * @param keyS
     * @return
     */
	public static String decodc(String myinfoS,String keyS) {
		String Algorithm = "DES"; //DES,DESede,Blowfish
		try {
			byte[] myinfo = hexStringToByte(myinfoS);
			byte[] key = hexStringToByte(keyS);
			DESKeySpec dks = new DESKeySpec(key);

			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Algorithm);
			SecretKey deskey = keyFactory.generateSecret(dks);

			//log.debug("解密前数据=[" + byte2hex(myinfo)+"]");

			Cipher c1 = Cipher.getInstance("DES/ECB/NoPadding");
			c1.init(Cipher.DECRYPT_MODE, deskey);

			byte[] cipherByte = c1.doFinal(myinfo);
			//log.debug("解密结果=[" + byte2hex(cipherByte)+"]");
			return byte2hex(cipherByte);

		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return null;
	}

	/**
	 *	des加密
	 * @param myinfoS
	 * @param keyS
     * @return
     */
	public static String encodc(String myinfoS,String keyS) {
		String Algorithm = "DES"; //DES,DESede,Blowfish
		try {
			byte[] myinfo = hexStringToByte(myinfoS);
			byte[] key = hexStringToByte(keyS);
			DESKeySpec dks = new DESKeySpec(key);

			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Algorithm);
			SecretKey deskey = keyFactory.generateSecret(dks);
			//log.debug("加密前数据=[" + byte2hex(myinfo)+"]");
			Cipher c1 = Cipher.getInstance("DES/ECB/NoPadding");
			//Cipher c1 = Cipher.getInstance("DES");
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			byte[] cipherByte = c1.doFinal(myinfo);
			//log.debug("加密结果=[" + byte2hex(cipherByte)+"]");
			return byte2hex(cipherByte);

		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return null;
	}
	//DES加密
	public static byte[] encodc(byte[] myinfo,byte[] key) {
		String Algorithm = "DES"; //DES,DESede,Blowfish
		try {
			DESKeySpec dks = new DESKeySpec(key);

			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Algorithm);
			SecretKey deskey = keyFactory.generateSecret(dks);
			//log.debug("加密前数据=[" + byte2hex(myinfo)+"]");
			Cipher c1 = Cipher.getInstance("DES/ECB/NoPadding");
			//Cipher c1 = Cipher.getInstance("DES");
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			byte[] cipherByte = c1.doFinal(myinfo);
			//log.debug("加密结果=[" + byte2hex(cipherByte)+"]");
			return cipherByte;

		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return null;
	}
	//DES加密
	 public static byte[] encryptDES(byte[] strkey, byte[] strdate)
		throws Exception {
		SecureRandom sr = new SecureRandom();
		DESKeySpec dks = new DESKeySpec(strkey);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey key = keyFactory.generateSecret(dks);
		Cipher encryptCipher = Cipher.getInstance("DES/ECB/NoPadding");
		encryptCipher.init(Cipher.ENCRYPT_MODE, key, sr);
		return encryptCipher.doFinal(strdate);
	}
	/**
	 * 加密
	 * @param data 待加密数�?
	 * @param key 密钥
	 * @return byte[] 加密数据
	 */	
	public static byte[] encrypt(byte[] data, byte[] key) throws Exception{
		//还原密钥
		Key k = toKey(key);
		/**
		 * 实例�?
		 * 使用PKCS7Padding填充方式，按如下代码实现
		 * Cipher.getInstance(CIPHER_ALGORITHM,"BC");
		 */
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		//初始化，设置为解密模�?
		cipher.init(Cipher.ENCRYPT_MODE, k);
		//执行操作
		return cipher.doFinal(data);
	}
	
	/**
	 * 生成密钥
	 * 
	 * @return byte[] 二进制密�?
	 */	
	public static byte[] initKey() throws Exception{
		/**
		 * 实例�?
		 * 使用128位或192位长度密�?
		 * KeyGenerator.getInstance(KEY_ALGORITHM,"BC");
		 */
		KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
		/**
		 * 初始�?
		 *使用128位或192位长度密钥，按如下代码实�?
		 *kg.init(128);
		 *kg.init(192);
		 */
		kg.init(168);
		//生成秘密密钥
		SecretKey secretKey = kg.generateKey();
		//获得密钥的二进制编码形式
		return secretKey.getEncoded();
	}
    //转换成十六进制字符串
    public static String byte2hex(byte[] b) {
        String hs="";
        String stmp="";

        for (int n=0;n<b.length;n++) {
            stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length()==1) 
            	hs=hs+"0"+stmp;
            else 
            	hs=hs+stmp;
            //if (n<b.length-1)  hs=hs+":";
        }
        return hs.toUpperCase();
    }
	public static byte[] hexStringToByte(String hex) {
		hex=hex.toUpperCase();
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] achar = hex.toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
		}
		return result;
	}
	private static byte toByte(char c) {
		byte b = (byte) "0123456789ABCDEF".indexOf(c);
		return b;
	}
	public static String Int2HexStr(int n)
	{
		String HexStr=Integer.toHexString(n);
		HexStr=HexStr.length()==1?"0"+HexStr:HexStr;
		return HexStr;
	}
	//MAC算法:
	public static String mac(String decKey,String orgData) throws Exception
	{
		byte[] dataByte=new byte[orgData.getBytes().length+1];
		System.arraycopy(orgData.getBytes(), 0, dataByte, 0, orgData.getBytes().length);
		dataByte[dataByte.length-1]=(byte)0x80;
						 
		byte[] addAscData=null;
						
		if(dataByte.length%8!=0){
			addAscData=new byte[(dataByte.length/8+2)*8];
			System.arraycopy(dataByte, 0, addAscData, 0, dataByte.length);
			for(int i =dataByte.length+1;i<addAscData.length;i++)
				addAscData[i]=0x00;
							
		}else{
			addAscData=new byte[dataByte.length+8];
			System.arraycopy(dataByte, 0, addAscData, 0, dataByte.length);
		}
		byte[] add={(byte)0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
		System.arraycopy(add, 0, addAscData, addAscData.length-8, 8);

		byte[] initKey={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
		String key=decKey;
		for(int i=0;i<addAscData.length/8;i++)
		{
			byte[]tmp=new byte[8];
			System.arraycopy(addAscData, i*8, tmp, 0, tmp.length);
							
			for(int j=0;j<8;j++){
				initKey[j]^=tmp[j];
			}			
			initKey=encryptDES(hexStringToByte(key),initKey);
		}
		return byte2hex(initKey).substring(0, 8);
	}

	//MAC验证:
	public static boolean macVerify(String orgMacStr,String merchantOrderTime,String macKey,String macStr) throws Exception {
		byte[] desKey = compute3DES(hexStringToByte(macKey),hexStringToByte(merchantOrderTime + "80"));
		String mac=mac(byte2hex(desKey),orgMacStr).substring(0, 8);
		log.debug("mac:"+mac);
		if(!mac.equals(macStr.toUpperCase())){
			return false;
		}
		return true;
	}

	//PIN加密
	public static String encryptPin(String orderTime,String Pin,String PinKey)
	{
		String mPin="";
		try{
			log.debug("orderTime:"+orderTime);
			String DataKey=encrypt3DES(orderTime+"80",PinKey);
			log.debug("DataKey:"+DataKey);
			
			Pin=Int2HexStr(Pin.length())+Pin;
			int PinLen=Pin.length();
			for(int j=0;j<16-PinLen;j++)
			{
				Pin+="F";
			}
			log.debug("Pin:"+Pin);
			mPin=byte2hex(encryptDES(hexStringToByte(DataKey),hexStringToByte(Pin)));
		}catch (Exception e) {
			e.printStackTrace();
		}
		return mPin;
	}
	//PIN加密
	public static String newEncryptPin(String Pan,String Pin,String PinKey){
		String DesPin="";
		try{
			Pan=Pan.substring(Pan.length()-13, Pan.length()-1);
			int PanLen=Pan.length();
			for(int i=0;i<16-PanLen;i++)
			{
				Pan="0"+Pan;
			}
			Pin=Int2HexStr(Pin.length())+Pin;
			int PinLen=Pin.length();
			for(int j=0;j<16-PinLen;j++)
			{
				Pin+="F";
			}
			byte[] res=TestDes.XORContent(hexStringToByte(Pin),hexStringToByte(Pan));
			log.debug("异或数据=["+Pan+"]["+Pin+"]");
			log.debug("异或的结果=["+byte2hex(res)+"]");
			if(PinKey.length()==32)
			{
				log.debug("=====加密开始========");
				log.debug("加密数据=["+byte2hex(res)+"]["+PinKey+"]");
				byte[] res1=DesUtil.compute3DES(TestDes.getDESKey(PinKey),res);
				DesPin=byte2hex(res1);
				log.debug("加密的结果=["+DesPin+"]");
				log.debug("=====加密结束========");
			}else{
				log.debug("=====加密开始========");
				log.debug("加密数据=["+byte2hex(res)+"]["+PinKey+"]");
				byte[] res1=encodc(res,TestDes.getDESKey(PinKey));
				DesPin=byte2hex(res1);
				log.debug("加密的结果=["+DesPin+"]");
				log.debug("=====加密结束========");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return DesPin;
	}
	
	
	//解密密文密码
	public static String getDecPin(String pinKey,String orderTime,String encPin)throws Exception{
		orderTime = orderTime+"80";
		byte[] b = compute3DES(hexStringToByte(pinKey), hexStringToByte(orderTime));
		byte[] bb =decodc(hexStringToByte(encPin),b);
		log.debug(byte2hex(bb));
		return byte2hex(bb);
		}
	//明文磁道数据加密
	public static String encryptStanderTranck(String orderTime,String randomNum,String trkKey,String track)
	{	
		orderTime=orderTime+"80";
		log.debug("orderTime:"+orderTime);
		log.debug("randomNum:"+randomNum);
		
		int trackLen=track.length();
		int n=track.length()/16;
		int mod=track.length()%16;
		
		String modData=track.substring(trackLen-mod);
		track=track.substring(0, n*16);
		
		log.debug("n:"+n);
		log.debug("mod:"+mod);
		
		String mTrack="";
		try {
			String aKey = byte2hex(compute3DES(hexStringToByte(trkKey),hexStringToByte(orderTime)));
			log.debug("aKey:"+aKey);
			String bKey=aKey+trkKey.substring(16);
			log.debug("bKey:"+bKey);
			String cKey=byte2hex(encryptDES(hexStringToByte(bKey),hexStringToByte(randomNum)));
			log.debug("cKey:"+cKey);
			log.debug("track:"+track);
			mTrack=byte2hex(encryptDES(hexStringToByte(cKey),hexStringToByte(track)));
			mTrack=trackLen+mTrack+modData;
		} catch (Exception e) {
			e.printStackTrace();
		}	
		return mTrack;
	}
	public static String newEncryptStanderTranck(String trkKey,String track){	
		log.debug("trkKey:"+trkKey);
		int trkLen=track.length();
		int mod=trkLen%16;
		log.debug("mod:"+mod);
		for(int i=0;i<16-mod;i++)
		{
			track+="F";
		}
		
		String mTrack="";
		try {
			log.debug("track:"+track);
			mTrack=byte2hex(compute3DES(hexStringToByte(trkKey), hexStringToByte(track)));
			mTrack=Int2HexStr(mTrack.length())+mTrack;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return mTrack;
	}
	public static String ySBEncryptStanderTranck(String trkKey,String track){
		log.debug("trkKey:"+trkKey);
		int trkLen=track.length();
		track = trkLen + track;
		int newTrkLen = track.length();
		int mod=newTrkLen%16;
		log.debug("mod:"+mod);
		for(int i=0;i<16-mod;i++){
			track+="0";
		}

		String mTrack="";
		try {
			log.debug("track:"+track);
			mTrack=byte2hex(compute3DES(hexStringToByte(trkKey),hexStringToByte(track)));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return mTrack;
	}

	/**
	 * 翰鑫磁道加密
	 * @param trkKey
	 * @param track
     * @return
     */
	public static String encryptHanXinTrack(String track, String trkKey, String masterKey){
		log.debug("主密钥:"+ masterKey);
		log.debug("密文trkKey:" + trkKey);
		if (null != masterKey)
			trkKey = decode3DES(trkKey, masterKey);
		log.debug("明文trkKey为: " + trkKey);
		String result = "";
		//判断磁道是否为奇数,如果为奇数就补位0
		int trkLen1=track.length();
		if (trkLen1%2 != 0){
			track += "0";
		}
		int trkLen2 = track.length();
		//截取磁道的后两位
		String f3 = track.substring(trkLen2-2);
		//从f3的位置开始,向前截取16位
		String f2 = track.substring(trkLen2-18, trkLen2-2);
		//剩下的部分
		String f1 = track.substring(0, trkLen2-18);
		//将f2做3des 双倍长加密
		String desF2 = encrypt3DES(f2, trkKey);
		//最后将f1,f2,f3依次拼接起来
		result = f1 + desF2 + f3;
		result = trkLen1 + result;
		return result;
	}
	
	//密文磁道数据解密
	public static String decryptStanderTranck(String tracKey,String orderTime,String randomNum,String track) throws Exception
	{
		orderTime = orderTime+"80";
		String trackLen = track.substring(0, 2);
		log.debug("trackLen:"+trackLen);
		int len = Integer.parseInt(trackLen);
		int n = len  / 16;
		String decTrac = track.substring(2, (n*16)+2);
		log.debug("decTrac:"+decTrac);
		byte[] tracKeyArr = hexStringToByte(tracKey);
		byte[] b = compute3DES(tracKeyArr, hexStringToByte(orderTime));
		String newTrackKey=byte2hex(b)+tracKey.substring(16);
		byte[] bb = encryptDES(hexStringToByte(newTrackKey), hexStringToByte(randomNum));
		byte[] bbb = decodc(hexStringToByte(decTrac),bb);
		decTrac = byte2hex(bbb);
		decTrac = decTrac + track.substring((n*16)+2);
		decTrac = decTrac.replace("D", "=").replace("d", "=");
		String last = decTrac.substring(decTrac.length()-1);
		if(last.equals("f") || last.equals("F")){
			decTrac = decTrac.substring(0,decTrac.length()-1);
		}
		return decTrac;
	}
	
	/**
	 * 生成8位DES密钥  转码的16位密钥
	 * @return
	 */
	public static String generate16Key(){
		KeyGenerator kg;
		try {
			kg = KeyGenerator.getInstance("DES");
			kg.init(56);
			SecretKey secretKey = kg.generateKey();
			byte[] key = secretKey.getEncoded();
			return byte2hex(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//E点支付明文磁道数据加密
	public static String ideaioeEncryptStanderTranck(String trkKey,String track,String MasterKey){
		if(null != MasterKey)
			trkKey=decode3DES(trkKey,MasterKey);
		int endID=2;
		if(track.length()%2==1) {
			endID=1;
		}
		String mTrk=track.substring(track.length()-16-endID, track.length()-endID);
		String mTrack="";
		try {
			String mTrk2=byte2hex(compute3DES(hexStringToByte(trkKey), hexStringToByte(mTrk)));
			mTrack=track.replaceAll(mTrk, mTrk2);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mTrack;
	}

	/**
	 * 生成8位DES密钥  转码的32位密钥
	 * @return
	 */
	public static String generate32Key(){
		return MD5.mD5ofStr(generate16Key());
	}

	/**
	 * Description 根据键值进行加密
	 * @param data
	 * @param key  加密键byte数组
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String data, String key) throws Exception {
		byte[] bt = encrypt(data.getBytes(), key.getBytes());
		String strs = new BASE64Encoder().encode(bt);
		return strs;
	}

	/**
	 * Description 根据键值进行解密
	 * @param data
	 * @param key  加密键byte数组
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public static String decrypt(String data, String key) throws Exception {
		if (data == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] buf = decoder.decodeBuffer(data);
		byte[] bt = decrypt(buf,key.getBytes());
		return new String(bt);
	}

	/**
	 * 加密
	 * @param src 数据源
	 * @param key 密钥，长度必须是8的倍数
	 * @return 返回加密后的数据
	 */
	public static byte[] encryptDes(byte[] src, byte[] key) {
		// DES算法要求有一个可信任的随机数源
		SecureRandom sr = new SecureRandom();
		try {
			// 从原始密匙数据创建DESKeySpec对象
			DESKeySpec dks = new DESKeySpec(key);
			// 创建一个密匙工厂，然后用它把DESKeySpec转换成
			// 一个SecretKey对象
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
			SecretKey securekey = keyFactory.generateSecret(dks);
			// Cipher对象实际完成加密操作,NoPadding为填充方式 默认为PKCS5Padding
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_NEW);
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
			// 现在，获取数据并加密
			// 正式执行加密操作
			return cipher.doFinal(src);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 生成密钥
	 *
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static byte[] initDesKey() throws NoSuchAlgorithmException {
		KeyGenerator kg = KeyGenerator.getInstance(DES);
		kg.init(56);
		SecretKey secretKey = kg.generateKey();
		return secretKey.getEncoded();
	}

	/**
	 * 解密
	 *
	 * @param src 数据源
	 * @param key 密钥，长度必须是8的倍数
	 * @return 返回解密后的原始数据
	 * @throws Exception
	 */
	public static byte[] decryptDes(byte[] src, byte[] key) {
		// DES算法要求有一个可信任的随机数源
		SecureRandom sr = new SecureRandom();
		try {
			// 从原始密匙数据创建一个DESKeySpec对象
			DESKeySpec dks = new DESKeySpec(key);
			// 创建一个密匙工厂，然后用它把DESKeySpec对象转换成
			// 一个SecretKey对象
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
			SecretKey securekey = keyFactory.generateSecret(dks);
			// Cipher对象实际完成解密操作
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_NEW);
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
			// 现在，获取数据并解密
			// 正式执行解密操作
			return cipher.doFinal(src);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

}
